package com.slz3.business.frame.task;

import com.aliyuncs.exceptions.ClientException;
import com.slz3.business.frame.api.sms.SmsUtilMishang;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.redis.Jedis;
import com.slz3.business.frame.util.JiGuangUtil;
import com.slz3.business.module.memberManagement.memMember.domain.MemMember;
import com.slz3.business.module.messageManagement.mesLog.domain.MesLog;
import com.slz3.business.module.messageManagement.mesLog.repository.MesLogRepository;
import com.slz3.business.module.messageManagement.mesTemplate.domain.MesTemplateKeys;
import com.slz3.business.module.systemManagement.sysUser.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ScheduledFuture;

import static com.slz3.business.frame.util.RedisClient.redisTemplate;

@Component
public class DynamicScheduleTaskSecond {
    private Map<String,ScheduledFuture<?>> map = new HashMap<String, ScheduledFuture<?>>();//跑过的定时器任务
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private SysUserRepository sysUserRepository;
    private MesLogRepository mesLogRepository;
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
        return new ThreadPoolTaskScheduler();
    }
    private ScheduledFuture<?> future;
    public void setCron(Date startTime,String cron,String activityId,String serTitle,String serContent,String temNum) {
        stopCron(activityId);//停止任务
        future = threadPoolTaskScheduler.schedule(new Runnable() {
            @Override
            public void run() {
                //根据 activityId 查找 需要发送的人 和 发送的内容
                System.out.println(activityId+"------------------------");
                //TODO  info  2list   member:uuid:info:uuid   message:uuid:2:list
                System.out.println("-------------定时发送短信-------------");
                //获取用户的手机号
                //TODO 用户类型指定 根据角色或者定义信息查找用户  UserMessageTypeEnum
                List<MemMember> all = Optional.ofNullable(Repositorys.memMember.findAll()).orElse(new ArrayList<MemMember>());
                //redis里面存所有用户数据  没有一个用户发送成功时 生成三个 hash 一个标识短信 一个标识 redis 一个标识 极光
                //批量保存所有 日志信息
                List<String> listnew = new ArrayList<String>();
                //保存所有数据后 发送短信
                boolean flag = true;//当全部发送成功时为true
                int intFlag = 0;//循环发送次数不能超过三次  如果发送超过三次 不再推送消息

                while(true&&intFlag<=2){
                    if(intFlag==0){
                        //遍历所有数据发送短信提醒
                        Map map =new HashMap();
                        map.put("MESSAGETYPE","XTHD");
                        if(Jedis.db0.get(MesTemplateKeys.getSingleTemplate(temNum))!=null){
                            String   content = Jedis.db0.get(MesTemplateKeys.getSingleTemplate(temNum)).toString();
                            map.put("XTHDMESSAGE",content);
                            map.put("activityId",activityId);
                            sendMessage(serTitle,all,map);
                        }else{
                            map.put("XTHDMESSAGE","系统活动消息");
                            map.put("activityId",activityId);
                            sendMessage(serTitle,all,map);
                        }
                    }else if(intFlag==1){
                        //判断是否还有数据未成功
                    }else{
                        //判断数据是否还有未成功
                    }
                    intFlag++;
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if(triggerContext.lastScheduledExecutionTime()==null){
                    ((SimpleTriggerContext)triggerContext).update(startTime,startTime,startTime);
                }
                CronTrigger trigger = new CronTrigger(cron);// 定时任务触发，可修改定时任务的执行周期
                Date nextExecDate = trigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
        System.out.println("定时器活动id-------------------------"+activityId);
        map.put(activityId,future);
    }

    public void stopCron(String activityId) {
        if(map.containsKey(activityId)){
            ScheduledFuture<?> nowFuture = map.get(activityId);
            nowFuture.cancel(true);
            System.out.print("--------------删除定时器成功----------");
        }
    }
    public static void sendMessage(String serTitle, List<MemMember> all,Map map){
        List<MesLog> list =new ArrayList<MesLog>();
        all.forEach(obj -> {
            MesLog mesLog = new MesLog();
            String content = "";
            try {
                SmsUtilMishang.sendSms(obj.getSerPhone(), map);
                mesLog.setSmsType(1);
            } catch (ClientException e) {
                mesLog.setSmsType(2);
                //重新发送
                e.printStackTrace();
            }
            try {
                Map jgmap = new HashMap<>();//活动类型
                Map hdmap = new HashMap<>();//
                /*Object o = Jedis.db0.get(RK.USER_APP_KEY_GENARATED__UUID.replace("${uuid}", obj.getUuid().toString()));*/
                switch (map.get("MESSAGETYPE").toString()){
                    case "SMS_151996608":
                        content = "您的订单已发货,请及时查收";
                        jgmap.put("type","orderMessage");
                        jgmap.put("serUuid",map.get("serOrderUuid"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(), content, "发货提醒", "", jgmap);
                        break;
                    case "SMS_151991549":
                        content = "您的未付款订单,剩余10分钟支付,请及时支付呦";
                        jgmap.put("type","orderMessage");
                        jgmap.put("serUuid",map.get("uuid"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(), content, "未支付提醒", "", jgmap);
                        break;
                    case "SMS_151996668"://抽奖活动即将开始
                        content = "您的活动即将开始，点击立即参与吧";
                        jgmap.put("type","dawMessage");
                        jgmap.put("hdDetailType","jf");
                        jgmap.put("hdDetailUuid","2222222222");
                        jgmap.put("serUuid",map.get("UUID"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(),content, "抽奖即将开始", "", jgmap);
                        /*JiGuangUtil.sendToRegistrationId(o.toString(), "觅上科技", "抽奖即将开始", "您的活动即将开始，点击立即参与吧", map.get("UUID").toString());*/
                        break;
                    case "SMS_151996674":
                        content = "您参与的活动已中奖，速速点击领取吧";
                        jgmap.put("type","dawMessage");
                        jgmap.put("serUuid",map.get("UUID"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(), content, "未领奖提醒", "", jgmap);
                            break;
                    case "SMS_151991559":
                        content = "您的订单已签收";
                        break;
                    case "XTHD"://TODO 系统消息 活动消息发送短信模板
                        content = "系统消息";
                        jgmap.put("type","xthdMessage");
                        jgmap.put("serUuid",map.get("activityId"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(),content, "系统消息", "", jgmap);
                        break;
                    case "SMS_151996100"://TODO 中奖提醒
                        content="中奖提醒";
                        jgmap.put("type","dawMessage");
                        jgmap.put("serUuid",map.get("hdUuid"));
                        JiGuangUtil.sendToRegistrationId(obj.getSerPhone(), content, "中奖提醒", "", jgmap);
                        break;
                }
               /* if(activityId.equals("")){

                }else{
                    JiGuangUtil.sendToAll("活动通知消息", "活动标题", "活动内容", "");
                }*/
                mesLog.setJgType(1);
            }catch(Exception ex){
                mesLog.setJgType(2);
            }
            mesLog.setUuid(UUID.randomUUID());
            mesLog.setSerTitle(serTitle);
            mesLog.setSendUserName("admin");
            mesLog.setReceiveUserName(obj.getSerUserName());
            mesLog.setReceiveUserCode(obj.getUuid());
            mesLog.setSerContent(content);
            //极光推送
            list.add(mesLog);
            if (list.size() > 1000) {
                saveToRedis(list);
                list.clear();
            }
        });
        if (list.size() > 0) {
            saveToRedis(list);
            list.clear();
        }
    }

    public  static void  saveToRedis(List<MesLog> list){

        List<MesLog> listDBnewLatest = Repositorys.mesLog.saveAll(list);
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    for (MesLog mesObject:listDBnewLatest){
                    if(mesObject.getJgType()==1&&mesObject.getSmsType()==1){
                        //成功
                        connection.set(String.format("%s:%s:%s:%s:%s","Service","Message","Member",mesObject.getReceiveUserCode(),"Info",mesObject.getUuid().toString()).getBytes(),mesObject.toString().getBytes());
                        connection.lPush(String.format("%s:%s:%s", "Service", "Message","Member",mesObject.getReceiveUserCode().toString()).getBytes(),mesObject.getUuid().toString().getBytes());
                    }
                }
                return null;
            }
        });
        list.clear();
    }
}

